package com.example.finalframe.interceptor;

import com.alibaba.fastjson.JSON;
import com.example.finalframe.aop.Authority;
import com.example.finalframe.common.ApiConstant;
import com.example.finalframe.common.ApiResult;
import com.example.finalframe.model.dto.RoleDto;
import com.example.finalframe.model.entity.RoleMenu;
import com.example.finalframe.service.intf.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
public class CheckRoleInterceptor implements HandlerInterceptor {
    @Autowired
    UserService userService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("权限验证preHandle被调用");
        // 上一个登录拦截器的userid
        long userId = Long.parseLong(String.valueOf(request.getAttribute("userId")));
        System.out.println("userId"+userId);
        if (this.getCheckRoleResult(handler,userId)) {
            request.setAttribute("userId",userId);
            return true;
        }
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = response.getWriter();
        String json = JSON.toJSONString(ApiResult.fail(ApiConstant.RESULT_NO_PERMISSION, "无权限访问"));
        out.append(json);
        out.flush();
        return false;
    }


    //判断用户的权限，是否满足所需要的访问权限
    private Boolean getCheckRoleResult(Object handler,long userId) {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            // 获取方法上的注解
            Authority authority = handlerMethod.getMethod().getAnnotation(Authority.class);
            // 如果方法上的注解为空 则获取类的注解
            if (authority == null) {
                authority = handlerMethod.getMethod().getDeclaringClass().getAnnotation(Authority.class);
            }
            // 注解不为空，判断权限
            if (authority != null) {
                Integer id = (int) userId;
                RoleDto roleDto = userService.findRoleByUserId(id);
                if (roleDto.getRoletype().toString().equals("0")) {
                    System.out.println("验证成功");
                    return true;
                }
            }
        }
        return true;
    }
}
